package com.android.volley.components.alipay;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;

import java.util.Map;

/**
 * Created by Kim on 2017/4/26.
 * 支付宝支付 工具类
 */

public class AlipayUtils {

    private static final int SDK_PAY_FLAG = 1;

    public static final String PAYMENT_OK = "9000";

    private AlipayCallBack alipayCallBack;

    /**
     * 支付宝支付业务
     *
     * @param activity 上下文
     */
    public void payV2(final Activity activity,final String orderInfo, AlipayCallBack alipayCallBack) {
        this.alipayCallBack = alipayCallBack;
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(activity);
                Map<String, String> result = alipay.payV2(orderInfo, true);
//                Utils.log("AlipayUtils", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    alipayCallBack.callBack(TextUtils.equals(resultStatus, PAYMENT_OK));
//                    if (TextUtils.equals(resultStatus, PAYMENT_OK)) {
//                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        Utils.log("AlipayUtils", "成功");
//                    } else {
//                        Utils.log("AlipayUtils", "失败");
//                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                    }
                    break;
                }
            }
        }
    };

    public interface AlipayCallBack{
        void callBack(boolean isSuccess);
    }



}
